package com.shiwaixiangcun.customer.ui.activity

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import butterknife.ButterKnife
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.GlobalConfig
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.AlertPhoneBean
import com.shiwaixiangcun.customer.interfaces.RequestPermissionType
import com.shiwaixiangcun.customer.ui.dialog.DialogLoginOut
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.JsonUtil
import com.tencent.smtt.export.external.interfaces.JsResult
import com.tencent.smtt.sdk.*
import kotlinx.android.synthetic.main.activity_doctor_detail.*
import kotlinx.android.synthetic.main.top_bar_white.*

/**
 * @author Administrator
 * Doctor详情
 */
class DoctorDetailActivity : BaseActivity(), View.OnClickListener {


    var urlBuilder = StringBuilder()

    private var id: Int = 0
    private var strToken: String? = null
    private var phone: String? = null

    /**
     * 清除Cookie
     *
     * @param context
     */
    private fun removeCookie(context: Context) {
        CookieSyncManager.createInstance(context)
        val cookieManager = CookieManager.getInstance()
        cookieManager.removeAllCookie()
        CookieSyncManager.getInstance().sync()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_doctor_detail)
        ButterKnife.bind(this)

        val extras = intent.extras
        if (extras != null) {
            id = extras.getInt("id")
            phone = extras.getString("phone")
        }
        strToken = AppSharePreferenceMgr.get(mContext, GlobalConfig.TOKEN, "") as String
        initViewAndEvent()


    }

    private fun initViewAndEvent() {
        back_left!!.setOnClickListener(this)
        tv_page_name!!.text = "专家主页"
        urlBuilder.append(GlobalApi.doctorDetail)
                .append("?id=")
                .append(id)
        Log.e(BUG_TAG, "医生详情" + urlBuilder.toString())
        //        removeCookie(mContext);
        docWeb!!.webChromeClient = MyWebChromeViewClient()
        docWeb!!.webViewClient = MyWebViewClient()
        docWeb!!.post {
            docWeb.loadUrl(urlBuilder.toString())
        }


    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK && docWeb!!.canGoBack()) {
            docWeb!!.goBack() // goBack()表示返回WebView的上一页面
            true
        } else {
            finish()
            false
        }
    }

    override fun onDestroy() {
        if (docWeb != null) {
            docWeb!!.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
            docWeb!!.clearHistory()

            (docWeb!!.parent as ViewGroup).removeView(docWeb)
            docWeb!!.destroy()
        }
        super.onDestroy()
    }


    override fun onClick(v: View) {
        when (v.id) {
            R.id.back_left -> finish()

            else -> {
            }
        }

    }

    private fun showDialog(phone: String) {
        val dialogLoginOut = DialogLoginOut(mContext, R.layout.item_dialog_call_phone)
        dialogLoginOut.setTitle("是否要拨打此电话？")
        dialogLoginOut.setMessage(phone)
        dialogLoginOut.setYesOnclickListener("是", DialogLoginOut.OnPositiveOnclickListener {
            dialogLoginOut.dismiss()
            requestPermission(phone)
        })

        dialogLoginOut.setNoOnclickListener("否") { dialogLoginOut.dismiss() }
        dialogLoginOut.show()
    }

    private fun requestPermission(number: String?) {
        //判断Android版本是否大于23
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)

            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CALL_PHONE),
                        RequestPermissionType.REQUEST_CODE_ASK_CALL_PHONE)
                return
            } else {
                callPhone(number)
            }
        } else {
            callPhone(number)
        }
    }


    /**
     * 注册权限申请回调
     * @param requestCode 申请码
     * @param permissions 申请的权限
     * @param grantResults 结果
     */
    @Override
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        when (requestCode) {
            RequestPermissionType.REQUEST_CODE_ASK_CALL_PHONE -> if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                callPhone(phone)
            } else {
                // Permission Denied
                Toast.makeText(this, "CALL_PHONE Denied", Toast.LENGTH_SHORT).show()
            }
            else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        }
    }

    /**
     * 拨号方法
     */
    @SuppressLint("MissingPermission")
    private fun callPhone(number: String?) {
        val intent = Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number))
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startActivity(intent)
    }
    /**
     * 处理Javascript的对话框，网站图标，网站title，加载进度等
     */
    private inner class MyWebChromeViewClient : WebChromeClient() {

        override fun onProgressChanged(view: WebView, newProgress: Int) {
            myProgressBar!!.visibility = View.VISIBLE
            if (newProgress == 100) {
                myProgressBar!!.visibility = View.GONE
            } else {
                if (View.INVISIBLE == myProgressBar!!.visibility) {
                    myProgressBar!!.visibility = View.VISIBLE
                }
                myProgressBar!!.progress = newProgress
            }
            super.onProgressChanged(view, newProgress)
        }

        override fun onJsAlert(view: WebView, url: String, message: String, result: JsResult): Boolean {
            if (message.contains("phone")) {
                val alertPhoneBean = JsonUtil.fromJson(message, AlertPhoneBean::class.java) ?: return super.onJsAlert(view, url, message, result)
                if (alertPhoneBean.data.phone != null) {

                    showDialog(alertPhoneBean.data.phone)
                }
                result.confirm()
                return true
            } else {
                return super.onJsAlert(view, url, message, result)
            }
        }
    }

    private inner class MyWebViewClient : WebViewClient() {

        override fun onLoadResource(view: WebView, url: String) {

            Log.i("tag", "onLoadResource url=" + url)
            super.onLoadResource(view, url)
        }

        override fun shouldOverrideUrlLoading(webview: WebView,
                                              url: String): Boolean {

            Log.i("tag", "intercept url=" + url)
            // 重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边
            webview.loadUrl(url)

            return true
        }

        override fun onPageFinished(view: WebView, url: String) {

            val title = view.title // 得到网页标题

            Log.e("tag", "onPageFinished WebView title=" + title)

        }

        override fun onReceivedError(view: WebView, errorCode: Int,
                                     description: String, failingUrl: String) {

            Toast.makeText(applicationContext, "加载错误",
                    Toast.LENGTH_LONG).show()
        }
    }


}
